package com.example.cardmatchinggame;

import java.util.ArrayList;
import java.util.List;

public class CardMatchingGame {
    private List<Card> cards;
    private int score;
    private int mode; // 2 for two-card matching, 3 for three-card matching

    public CardMatchingGame(int cardCount, int mode) {
        this.mode = mode;
        this.score = 0;
        Deck deck = new Deck(cardCount, mode);
        this.cards = deck.getCards();
    }

    public void chooseCardAtIndex(int index) {
        if (index < 0 || index >= cards.size()) {
            return;
        }

        Card card = cards.get(index);
        
        if (card.isMatched() || card.isFaceUp()) {
            return;
        }

        if (mode == 2) {
            // 双卡模式
            List<Card> faceUpCards = getFaceUpCards();
            
            if (faceUpCards.size() == 0) {
                card.setFaceUp(true);
            } else if (faceUpCards.size() == 1) {
                card.setFaceUp(true);
                int matchScore = card.match(faceUpCards.get(0));
                score += matchScore;
                
                if (matchScore <= 0) {
                    // 不匹配，翻回去
                    card.setFaceUp(false);
                    faceUpCards.get(0).setFaceUp(false);
                }
            }
        } else if (mode == 3) {
            // 三卡模式
            List<Card> faceUpCards = getFaceUpCards();
            
            if (faceUpCards.size() < 2) {
                card.setFaceUp(true);
            } else if (faceUpCards.size() == 2) {
                card.setFaceUp(true);
                int matchScore = card.match(faceUpCards.get(0), faceUpCards.get(1));
                score += matchScore;
                
                if (matchScore <= 0) {
                    // 不匹配，翻回去
                    card.setFaceUp(false);
                    faceUpCards.get(0).setFaceUp(false);
                    faceUpCards.get(1).setFaceUp(false);
                }
            }
        }
    }

    private List<Card> getFaceUpCards() {
        List<Card> faceUpCards = new ArrayList<>();
        for (Card card : cards) {
            if (card.isFaceUp() && !card.isMatched()) {
                faceUpCards.add(card);
            }
        }
        return faceUpCards;
    }

    public Card cardAtIndex(int index) {
        if (index >= 0 && index < cards.size()) {
            return cards.get(index);
        }
        return null;
    }

    public int getScore() {
        return score;
    }

    public int getCardCount() {
        return cards.size();
    }

    public void reset() {
        Deck deck = new Deck(cards.size(), mode);
        this.cards = deck.getCards();
        this.score = 0;
    }
}
